<template>
  <div class="about">
    <header>
      <span @click="$router.back()">返回</span>
      <section>购物清单</section>
      <span @click="isEit=!isEit">{{isEit?'编辑':'完成'}}</span>
    </header>
    <ul>
      <li v-for="(item,index) in list" :key="index">
        <input type="checkbox" v-model="item.check" @change="checkOne">
        <img src="../assets/logo.png" alt="">
        <section>
          <h5>{{item.name}}</h5>
          <p style="color:red">￥{{item.price}}</p>
          <span>库存{{item.payNum}}件</span>
        </section>
        <div>
          <p @click="item.buyNum++">+</p>
          <p>{{item.buyNum}}</p>
          <p @click="item.buyNum==1?1:item.buyNum--">-</p>
        </div>
      </li>
    </ul>
    <div class="foot">
      <section>
        <input type="checkbox" v-model="isCheck" @change="$store.commit('checkAll',isCheck)">
        全选
      </section>
      <span>合计：{{allPrice}}</span>
      <span class="foot-rt" @click="del">{{isEit?'去结算':'删除所选'}}（{{allNum}}）</span>
    </div>
  </div>
</template>

<script>
import { ref, reactive, toRefs,computed } from "vue";
import { useStore } from 'vuex';
export default {
  setup() {
    const { state,commit } = useStore();
    const data = reactive({
      list: computed(() => state.cartList),
      isEit: true, // 默认编辑状态
      isCheck: state.cartList.every(item => item.check),
      allPrice: computed(() => {
        let price = 0;
        state.cartList.forEach(item => {
          if (item.check){
            price+=item.buyNum*item.price
          }
        })
        return price;
      }),
      allNum: computed(() => {
        let num = 0;
        state.cartList.forEach(item => {
          if (item.check){
            num+=item.buyNum
          }
        })
        return num;
      })
    })

    const checkOne = () => { // 单选事件
       data.isCheck = data.list.every(item => item.check);
       commit('kong');
    }

    const del = () => { // 删除的函数
       if (data.isEit) return;
       commit('delect');
       data.isCheck = false;
    }
    return {
      ...toRefs(data),
      checkOne,
      del
    }
  },
};
</script>
<style lang="scss" scoped>
.about{
  height: 100%;
  background: #e9e9e9;
  header{
    height: 45px;
    display: flex;
    align-items: center;
    background: #fff;
    span{
      width: 60px;
      text-align: center;
    }
    section{
      flex: 1;
      text-align: center;
    }
  }
}
ul{
  height: calc(100% - 95px);
  overflow: auto;
  li{
    display: flex;
    padding: 10px;
    background: #fff;
    margin-bottom: 10px;
    align-items: center;
    img{
      width: 70px;
    }
    section{
      flex: 1;
    }
  }
}
.foot{
  height: 50px;
  display: flex;
  justify-content: space-between;
  background: #fff;
  align-items: center;
  section{
    margin-left: 10px;
  }
  .foot-rt{
    background: #8d58f6;
    color: #fff;
    line-height: 50px;
    padding: 0 10px;
  }
}
</style>